package fr.bstevant.android.WifiNotify;

import android.app.Activity;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle; 
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.view.View;
import android.view.View.OnClickListener; 
import android.widget.CheckBox;
import android.widget.TextView;
import android.content.SharedPreferences;



public class WifiNotify extends Activity {
	public static final String PREFS_NAME = "WifiNotifyPrefs";
	private int YOURAPP_NOTIFICATION_ID = 20100114;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	WifiManager wm;
    	WifiInfo wifiInfo;
    	final NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    	
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

    	// Preferences reading
    	SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    	final SharedPreferences.Editor editor = settings.edit();
    	Boolean notifEnabled = settings.getBoolean("chkNotifEnabled", false);

    	// Set checkbox according to preference
    	final CheckBox checkBox = (CheckBox) findViewById(R.id.RegisterCheckBox);
    	checkBox.setChecked(notifEnabled);
    	
        /* Get WiFi info */
        wm = (WifiManager)getSystemService(Context.WIFI_SERVICE);
        wifiInfo = wm.getConnectionInfo();
        // if connected
        if (wifiInfo.getSSID() != null) {
        	((TextView)findViewById(R.id.SSID_Text)).setText(wifiInfo.getSSID());
        	((TextView)findViewById(R.id.Signal_Text)).setText(Integer.toString(wifiInfo.getRssi()));
        } else {
        	((TextView)findViewById(R.id.SSID_Text)).setText("Null");
        	((TextView)findViewById(R.id.Signal_Text)).setText("0");        	
        }
        
        /* Enable/Disable notification */
        findViewById(R.id.RegisterCheckBox).setOnClickListener(new OnClickListener(){
        	public void onClick(View v) {
        		editor.putBoolean("chkNotifEnabled", checkBox.isChecked());
        		editor.commit();
        		if (!checkBox.isChecked()) nm.cancel(YOURAPP_NOTIFICATION_ID);
        	}
        });
        
        
        /* Start WiFi settings. */
        findViewById(R.id.btn_settings).setOnClickListener(new OnClickListener(){
               public void onClick(View v) {
            	   Intent i = new Intent(Settings.ACTION_WIFI_SETTINGS);
                   startActivity(i);
               }
        });
        
    }

}